package com.mo.controller;

import com.github.pagehelper.PageHelper;
import com.mo.common.domain.AjaxResult;
import com.mo.common.domain.Result;
import com.mo.domain.User;
import com.mo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author msy
 * @date 2022/2/22
 */
@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**用户主页面*/
    @GetMapping()
    public String user(ModelMap mmap){
        mmap.put("total",userService.selectCount());
        return "index";
    }

    /**添加页面跳转*/
    @GetMapping("insert")
    public String add(){
        return "add";
    }

    /**修改页面跳转*/
    @GetMapping("update")
    public String update(@RequestParam("id") Long id, ModelMap map){
        map.put("user",userService.selectUserById(id));
        return "update";
    }

    /**详情页面跳转*/
    @GetMapping("detail/{id}")
    public String detail(@PathVariable("id")Long id,ModelMap map){
        map.put("user",userService.selectUserById(id));
        return "detail";
    }

    /**页码处理*/
    @GetMapping("/pagination")
    @ResponseBody
    public AjaxResult pagination(){
        return AjaxResult.successObj(userService.selectCount());
    }

    /**数据列表*/
    @PostMapping("/list")
    @ResponseBody
    public AjaxResult list(@RequestBody Result<User> result,ModelMap mmap){
        User user = result.getObject();
        Integer pageNum = result.getPageNum();
        Integer pageSize = result.getPageSize();
        PageHelper.startPage(pageNum,pageSize);
        List<User> users = userService.selectUserList(user);
        return AjaxResult.successObj(users);
    }

    /**新增*/
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(User user){
        Integer result = userService.insertUser(user);
        return result>0?AjaxResult.success():AjaxResult.error();
    }

    /**修改*/
    @PostMapping("/update")
    @ResponseBody
    public AjaxResult update(User user){
        Integer result = userService.updateUser(user);
        return result>0?AjaxResult.success():AjaxResult.error();
    }

    /**删除*/
    @GetMapping("remove")
    @ResponseBody
    public AjaxResult remove(@RequestParam Long id){
        Integer result = userService.removeById(id);
        return result>0?AjaxResult.success():AjaxResult.error();
    }
}
